package math;

public class AddMinusMultiDivideByBit {

    public static int add(int a, int b) {
        int sum = a;
        while (b != 0) {
            sum = a ^ b;
            b = (a & b) << 1;
            a = sum;
        }

        return sum;
    }

    public static int negNum(int n) {
        return add(~n, 1);
    }

    public static int minus(int a, int b) {
        return add(a, negNum(b));
    }

    public static int multi(int a, int b) {
        int res = 0;
        while (b != 0) {
            // 只要最低位是1，就+上一个a
            if ((b & 1) != 0) {
                res = add(res, a);
            }

            // 每循环一次a算数左移一位
            a <<= 1;
            // 每循环一次b逻辑右移一位
            b >>>= 1;
        }

        return res;
    }

    public static boolean isNeg(int n) {
        return n < 0;
    }

    public static int div(int a, int b) {
        int x = a < 0 ? negNum(a) : a;
        int y = b < 0 ? negNum(b) : b;

        int res = 0;

        for (int i = 31; i > -1; i = minus(i, 1)) {
            if ((x >> i) >= y) {
                res |= (1 << i);
                x = minus(x, y << i);
            }
        }
        // a b符号不相同 ？ res的补码：res;
        return isNeg(a) ^ isNeg(b) ? negNum(res) : res;
    }
}
